#include <myhead.h>
#include "service.h"
#include "server.h"

static ol_link_t* L;//在线用户列表

void service_init(){
	L=ol_link_create();
}
//********** 发消息 *******************
void service_sendMsg(char* destname, char* buf, int len){
	ol_data_t* data=ol_link_findByName(destname);
	if(data == NULL){
		return;//不在线，那就不发
	}
	server_sendto(data->addr, data->port, buf, len);
}


//********** 链表的实现 ****************
ol_link_t* ol_link_create(){
	ol_link_t* L=(ol_link_t*)malloc(sizeof(ol_link_t));
	L->next=NULL;
	L->len=0;
	return L;
}

void ol_link_destroy(){
	ol_node_t* p = L->next;
	for(int i=0;i<L->len;i++){
		ol_node_t* t=p;
		p=p->next;
		free(t);
	}
	free(L);
}

void ol_link_insert(char* name, char* addr, 
		int port, long hearttime){
	ol_node_t* p=(ol_node_t*)malloc(sizeof(ol_node_t));
	p->next=NULL;
	strcpy(p->data.loginname, name);
	strcpy(p->data.addr, addr);
	p->data.port=port;
	p->data.hearttime=hearttime;
	//
	p->next=L->next;
	L->next=p;
	L->len++;
}

ol_data_t* ol_link_findByName(char* name){
	ol_node_t* p=L->next;
	for(int i=0;i<L->len;i++){
		if(strcmp(p->data.loginname, name) == 0){
			return &p->data;
		}
		p=p->next;
	}
	return NULL;
}

void ol_link_updateByName(char* name, char* addr, 
		int port, long hearttime){
	ol_node_t* p=L->next;
	for(int i=0;i<L->len;i++){
		if(strcmp(p->data.loginname, name) == 0){//bingo，修改之
			strcpy(p->data.addr, addr);
			p->data.port=port;
			p->data.hearttime=hearttime;
			return;
		}
		p=p->next;
	}
}

void ol_link_removeByName(char* name){
	ol_node_t* p=L->next;
	ol_node_t* pre=L;
	for(int i=0;i<L->len;i++){
		if(strcmp(p->data.loginname, name) == 0){//bingo
			pre->next=p->next;
			free(p);
			L->len--;
			return;
		}
		pre=p;
		p=p->next;
	}
}

void ol_link_show(){
	ol_node_t* p=L->next;
	printf("用户在线列表:\n");
	printf("序号\t用户名\t登录IP\t\tPORT\t最近心跳时间\n");
	for(int i=0;i<L->len;i++){
		printf("%02d\t%s\t%s\t%d\t%ld\n", i+1, p->data.loginname,
				p->data.addr, p->data.port, p->data.hearttime);	
		p=p->next;
	}	
}
//********** 链表的实现:END ****************





